import request from '@/utils/request'
import jwtDecode from 'jwt-decode'
import { getToken, setToken, removeToken, getRefreshToken, setRefreshToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'
import { Message } from 'element-ui'

const state = {
  token: getToken(),
  refreshToken: getRefreshToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  editStatus: {},
  // 快捷入口
  routeList: JSON.parse(localStorage.getItem('menuList')) ? JSON.parse(localStorage.getItem('menuList')) : [
    { title: 'options1', value: '' },
    { title: 'options2', value: '' },
    { title: 'options3', value: '' },
    { title: 'options4', value: '' },
    { title: 'options5', value: '' },
    { title: 'options6', value: '' },
    { title: 'options7', value: '' }
  ],
  // 报警消息默认值
  selectValue: 0,
  // 重置
  changeValue: 0,
  // 表单是否有值
  formValue: JSON.parse(localStorage.getItem('formValue')) || '',
  // 搜索框部门改变
  departmentValue: '',
  // 是否进入实时定位页面
  pageData: 0,
  // 考勤统计时间
  attendanceDate: {
    EnterTimeStart: null,
    EnterTimeEnd: null,
    status: false
  },
  // 拍照保存照片
  addPhoto: '',
  // 保存查询对象
  serchObj: JSON.parse(localStorage.getItem('serchObj')) || {},
  // 展示闸机数据
  gateSwaitch: JSON.parse(localStorage.getItem('gateSwaitch')) || '展示',
}

const mutations = {
  // 展示闸机数据
  SET_GATESWAITCH: (state, gateSwaitch) => {
    state.gateSwaitch = gateSwaitch
    localStorage.setItem('gateSwaitch', JSON.stringify(gateSwaitch))
  },
  // 保存查询对象
  SET_SERCHOBJ: (state, serchObj) => {
    state.serchObj = serchObj
    localStorage.setItem('serchObj', JSON.stringify(serchObj))
  },
  // 拍照保存照片
  SET_ADDPHOTO: (state, addPhoto) => {
    state.addPhoto = addPhoto
  },
  // 查询重复时使用
  SET_EDITSTATUS: (state, value) => {
    state.editStatus = value
  },
  // token
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // refreshtoken
  SET_REFRESHTOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken
  },
  // 用户id
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  // 用户名称
  SET_NAME: (state, name) => {
    state.name = name
  },
  // 用户头像
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  // 用户权限
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  // 快捷菜单
  SET_ROUTER: (state, routeArray) => {
    state.routeList = routeArray
    localStorage.setItem('menuList', JSON.stringify(routeArray))
  },
  // 报警消息默认值
  SET_SELECTVALUE: (state, selectValue) => {
    state.selectValue = selectValue
  },
  // 重置
  SET_CHANGEVALUE: (state, changeValue) => {
    state.changeValue = changeValue
  },
  // 表单是否有值
  SET_FORMVALUE: (state, formValue) => {
    state.formValue = formValue
    localStorage.setItem('formValue', JSON.stringify(formValue))
  },
  // 是否进入实时定位页面
  SET_PAGEDATA: (state, pageData) => {
    state.pageData = pageData
  },
  // 搜索框部门改变
  SET_DEPARTMENTVALUE: (state, departmentValue) => {
    state.departmentValue = departmentValue
  },
  // 考勤统计时间
  SET_ATTENDANCEDATE: (state, attendanceDate) => {
    state.attendanceDate = attendanceDate
  }
}

const actions = {
  setGateSwaitch({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_GATESWAITCH', data)
      resolve()
    })
  },
  setSerchObj({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_SERCHOBJ', data)
      resolve()
    })
  },
  // 拍照
  setAddPhoto({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_ADDPHOTO', data)
      resolve()
    })
  },
  // 考勤统计时间
  setAttendanceDate({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_ATTENDANCEDATE', data)
      resolve()
    })
  },
  // 部门改变，修改职位用到
  setDepartmentValue({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_DEPARTMENTVALUE', data)
      resolve()
    })
  },
  // 进出实时定位页面
  setPageData({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_PAGEDATA', data)
      resolve()
    })
  },
  // 表单的值
  setFormValue({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_FORMVALUE', data)
      resolve()
    })
  },
  // 重置表单
  setChangeValue({ commit, state }) {
    return new Promise((resolve, reject) => {
      let data = state.changeValue + 1
      commit('SET_CHANGEVALUE', data)
      resolve()
    })
  },
  // 设置报警消息默认值
  setDefult({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_SELECTVALUE', data)
      resolve()
    })
  },
  // 设置快捷菜单
  quickMenu({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_ROUTER', data)
      resolve()
    })
  },
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', userInfo.token)
      commit('SET_REFRESHTOKEN', userInfo.refresh_token)
      setToken(userInfo.token)
      setRefreshToken(userInfo.refresh_token)
      resolve()
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const { user } = jwtDecode(getToken())
      console.log(user)
      if (!user) {
        reject('Verification failed, please Login again.')
      }

      if (user.IsAdmin) {
        user.roles = ['admin']
      } else {
        user.roles = ['user']
      }

      const { roles, FirstName, user_id } = user

      // roles must be a non-empty array
      if (!roles || roles.length <= 0) {
        reject('getInfo: roles must be a non-null array!')
      }
      commit('SET_ROLES', roles)
      commit('SET_NAME', FirstName)
      // commit('SET_AVATAR', 'https://cn.vuejs.org/images/logo.png')
      // commit('SET_INTRODUCTION', user_id)
      resolve(user)
    })
  },
  setEdit({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit('SET_EDITSTATUS', data)
      resolve()
    })
  },
  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit('SET_TOKEN', '')
      commit('SET_REFRESHTOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_ROUTER', [
        { title: 'options1', value: '' },
        { title: 'options2', value: '' },
        { title: 'options3', value: '' },
        { title: 'options4', value: '' },
        { title: 'options5', value: '' },
        { title: 'options6', value: '' },
        { title: 'options7', value: '' }
      ])
      removeToken()
      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })
  },

  resetToken({ commit, state }, data) {
    return new Promise(resolve => {
      commit('SET_TOKEN', data.token)
      commit('SET_REFRESHTOKEN', data.refresh_token)
      setToken(data.token)
      setRefreshToken(data.refresh_token)
      resolve()
    })
  },

  // remove token
  removeToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_REFRESHTOKEN', '')
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, {
        root: true
      })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
